package controllers;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import models.Batch;
import models.Commodity;
import models.Order;
import models.BaseEntity.PeopleType;
import models.Order.OrderStatus;
import models.OrderItem;
import models.QueryBean;
import models.RemittanceConfirm;
import models.ShoppingCar;
import models.User;
import models.UserGroup;
import play.data.validation.MinSize;
import play.data.validation.Required;
import play.data.validation.Valid;
import play.mvc.Controller;
import play.mvc.With;
import service.CommoditiesService;
import service.OrderService;

@With(Secure.class)
public class Users extends Controller {

	/**
	 * 用户中心主页
	 * @throws Throwable 
	 */
	public static void index() throws Throwable {
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		if(user != null) {
			UserGroup group = getUserGroup(user.groups);
			render(user, group);
		}
		Secure.login();
	}
	
	/**
	 * 用户组搜索
	 * @param groups
	 * @return
	 */
	private static UserGroup getUserGroup(List<UserGroup> groups) {
		UserGroup result = groups.get(0);
		for(UserGroup group : groups) {
			if(group.priority > result.priority) {
				result = group;
			}
		}
		return result;
	}

	/**
	 * 编辑用户资料页面。
	 */
	public static void edit() {
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		render(user);
	}

	/**
	 * 编辑用户密码页面。
	 */
	public static void editPassword() {
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		render(user);
	}
    
	/**
	 * 保存用户密码。
	 * @param id
	 * @param newpassword
	 * @param oldpassword
	 * @param repassword
	 */
	public static void updatePassword(
			@Required Long id, 
			@Required @MinSize(6) String newpassword, 
			@Required @MinSize(6) String oldpassword, 
			@Required @MinSize(6) String repassword) {
		User user = User.findById(id);
		if(validation.hasErrors()) {
			render("@editPassword", user, newpassword, oldpassword, repassword);
		}
		
		if(user == null || user.password == null 
				|| !user.password.trim().equals(oldpassword.trim())) {
			validation.addError("oldpassword", "旧密码不正确");
			render("@editPassword", user, newpassword, oldpassword, repassword);
		}
		
		if(!newpassword.trim().equals(repassword.trim())) {
			validation.addError("repassword", "确认密码不正确");
			render("@editPassword", user, newpassword, oldpassword, repassword);
		}
		
		user.password = newpassword;
		
		user.resetModifier(user);
		
		user.save();
		validation.addError("validateRestle", "SUCC");
		render("@editPassword", user);
	}

	/**
	 * 保存用户资料。
	 * @param user
	 */
	public static void update(@Valid User user) {
		if(validation.hasErrors()) {
			params.flash(); // add http parameters to the flash scope
			validation.keep(); // keep the errors for the next request
			render("@edit", user);
		}
		
		User oriUser = User.findById(user.getId());
		oriUser.question = user.question;
		oriUser.answer = user.answer;
		oriUser.salesmode = user.salesmode;
		oriUser.deliveryAddress = user.deliveryAddress;
		oriUser.zipcode = user.zipcode;
		oriUser.phoneNo = user.phoneNo;
		oriUser.qqNo = user.qqNo;
		oriUser.msnNo = user.msnNo;
		oriUser.email = user.email;
		
		oriUser.resetModifier(oriUser);

		user.save();
		validation.addError("validateRestle", "SUCC");
		render("@edit", user);
	}
	
	/**
	 * 注册页面。
	 */
	public static void register(){
		render();
	}
    
	/**
	 * 提交注册信息
	 * 
	 * @param user
	 */
	public static void commitRegisterInfo(@Valid User user){
		//验证会员输入
		validation.minSize("user.name", 6);
		validation.minSize("user.password", 6);
		if(validation.hasErrors()) {
			render("@register", user);
		}
		
		//设置会员级别
		UserGroup group = UserGroup.find("byName", "普通会员").first();
		List<UserGroup> groups = new ArrayList<UserGroup>();
		groups.add(group);
		
		user.groups = groups;
		user.createAt = new Date();
		user.creatorType = PeopleType.USER;
		user.createByUser = user;
		
		//插入用户数据
		user.save();
		
		//进入管理主页面
		render("@index", user,group);
	}
	
	/**
	 * 最新到货列表页面。
	 */
	public static void newArrivals(QueryBean queryBean) {
		if(queryBean == null) {
			queryBean = new QueryBean();
		}
		StringBuilder sql = new StringBuilder();
		sql.append("onSaleStatus != ? ");
		if(queryBean.keyword != null && queryBean.keyword.trim().length() > 0) {
			sql.append("and (SN like '%" + queryBean.keyword + "%' ");
			sql.append("or name like '%" + queryBean.keyword + "%') ");
		}
		sql.append("order by createAt, lastModifiedAt desc");
		if(queryBean.orderby != null && queryBean.orderby.trim().length() > 0) {
			sql.append(", " + queryBean.orderby);
		}
		
		//页数计算
		queryBean.totalQuantity = new Commodity().count(sql.toString(), 
				Commodity.OnSaleStatus.OFFSALE);
		queryBean.totalPage = queryBean.totalQuantity/queryBean.quantityEachPage;
		if(queryBean.totalQuantity%queryBean.quantityEachPage > 0) queryBean.totalPage++;
		if(queryBean.totalPage < queryBean.currentPage) {
			queryBean.currentPage = queryBean.totalPage;
		}
		
		//新品推荐;
		List<Commodity> newArraivals = Commodity.find(sql.toString(), 
				Commodity.OnSaleStatus.OFFSALE)
			.fetch((int)queryBean.currentPage, queryBean.quantityEachPage);
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		CommoditiesService.setCommodityPriceByUser(newArraivals, user);
		render(newArraivals, queryBean);
	}

	/**
	 * 最新下架商品页面。
	 */
	public static void newOffSale(QueryBean queryBean) {
		if(queryBean == null) {
			queryBean = new QueryBean();
		}
		
		StringBuilder sql = new StringBuilder();
		sql.append("onSaleStatus = ? ");
		if(queryBean.keyword != null && queryBean.keyword.trim().length() > 0) {
			sql.append("and (SN like '%" + queryBean.keyword + "%' ");
			sql.append("or name like '%" + queryBean.keyword + "%') ");
		} 
		sql.append("order by createAt, lastModifiedAt desc");
		if(queryBean.orderby != null && queryBean.orderby.trim().length() > 0) {
			sql.append(", " + queryBean.orderby);
		}
		
		//页数计算
		queryBean.totalQuantity = Commodity.count(sql.toString(), 
				Commodity.OnSaleStatus.OFFSALE);
		queryBean.totalPage = queryBean.totalQuantity/queryBean.quantityEachPage;
		if(queryBean.totalQuantity%queryBean.quantityEachPage > 0) queryBean.totalPage++;
		if(queryBean.totalPage < queryBean.currentPage) {
			queryBean.currentPage = queryBean.totalPage;
		}
		
		//下架商品。
		List<Commodity> newOffSale = Commodity.find(sql.toString(), 
				Commodity.OnSaleStatus.OFFSALE)
			.fetch((int)queryBean.currentPage, queryBean.quantityEachPage);
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		CommoditiesService.setCommodityPriceByUser(newOffSale, user);
		render(newOffSale, queryBean);
	}
	
	/**
	 * 订单页面。
	 * @param queryBean
	 */
	public static void order(QueryBean queryBean) {
		if(queryBean == null) {
			queryBean = new QueryBean();
		}
		
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		
		String sql = "user.id = ? order by orderStatus, createAt desc, lastModifiedAt desc";
		
		//页数计算
		queryBean.totalQuantity = Order.count(sql, user.id);
		queryBean.totalPage = queryBean.totalQuantity/queryBean.quantityEachPage;
		if(queryBean.totalQuantity%queryBean.quantityEachPage > 0) queryBean.totalPage++;
		if(queryBean.totalPage < queryBean.currentPage) {
			queryBean.currentPage = queryBean.totalPage;
		}
		//orders
		List<Order> orders = Order.find(sql, user.id).fetch(
				(int)queryBean.currentPage, queryBean.quantityEachPage);
		render(orders, queryBean);
	}
}